﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using V5_Common;

namespace V5_EShop.Admin {
    public partial class Admin_Login : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {

        }

        protected void btnLogin_Click(object sender, EventArgs e) {
            string AdminName = this.txtAdminName.Text;
            string AdminPwd = this.txtAdminPwd.Text;

            string VerifyCode = txtVerifyCode.Text;
            DateTime LoginTime = DateTime.Now;
            string LoginIP = HttpsHelper.GetIP;

            if (AdminName == "" || AdminName == null) {
                JsHelper.AlertAndGoHistory("用户名不能为空!", -1);
                return;
            }
            if (AdminPwd == "" || AdminPwd == null) {
                JsHelper.AlertAndGoHistory("密码不能为空!", -1);
                return;
            }
            if (VerifyCode == "" || VerifyCode == null) {
                JsHelper.AlertAndGoHistory("验证码不能为空!", -1);
                return;
            }
            else if (VerifyCode != InputHelper.SetString(Session["LoginCode"])) {
                JsHelper.AlertAndGoHistory("验证码输入不正确!", -1);
                return;
            }
            AdminPwd = InputHelper.MD5(AdminPwd, 16);
            var q = from p in V5.DB.ModelAdmins
                    where p.AdminName == AdminName && p.AdminPwd == AdminPwd
                    select p;
            var model = q.FirstOrDefault();
            if (model == null || q.FirstOrDefault().ID == 0) {
                PrHelper.RegClientAlertAndRedirect(this, "对不起!用户名或者密码错误!", "Admin_Login.aspx");
            }
            else {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(AdminName, false, 20);
                string str1 = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, str1);
                cookie.Expires = DateTime.Now.AddMinutes(40);
                this.Context.Response.Cookies.Add(cookie);
                HttpCookie cookie1 = new HttpCookie("adminid", model.ID.ToString());
                cookie1.Expires = DateTime.Now.AddMinutes(40);
                HttpCookie cookie2 = new HttpCookie("adminname", model.AdminName.ToString());
                cookie2.Expires = DateTime.Now.AddMinutes(40);
                //添加cookie值
                this.Context.Response.Cookies.Add(cookie1);
                this.Context.Response.Cookies.Add(cookie2);
                Response.Redirect("Admin_Index.aspx");
            }
        }
    }
}
